package au.com.bus4u.service.impl;

import au.com.bus4u.dao.DaoSupport;
import au.com.bus4u.exception.ServiceException;
import au.com.bus4u.service.AuctionService;
import au.com.bus4u.service.OrderService;
import au.com.bus4u.utils.DateUtil;
import au.com.bus4u.utils.PageData;
import au.com.bus4u.utils.UuidUtil;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service("auctionService")
public class AuctionServiceImpl implements AuctionService {

    @Autowired
    private DaoSupport daoSupport;
    private String mapper = "AuctionMapper.";
    @Autowired
    private OrderService orderService;
    @Value("${min-auction-amount}")
    private Double minAuctionAmount;//最低竞拍金额
    @Value("${max-auction-count}")
    private Integer maxAuctionCount;//订单竞拍最大参与人数

    @Override
    public int save(PageData pd) throws Exception {

        //检测非空数据
        checkNonEmptyData(pd);

        //检测该参与竞拍的服务人员之前是否参与此订单 如果参数了 则执行更新操作
        Integer order_id = Integer.parseInt(pd.get("order_id").toString());
        //通过订单id查询此订单的状态

        Integer order_status = orderService.findStatusById(order_id);
        if( order_status != 4){
            throw new ServiceException("竞拍失败:订单已失效,该订单状态(order_status)为"+order_status);
        }
        String server_user_id = getCurrentUserID();
        Integer auctionCountByServerId = findByOrderIdAndServerId(order_id, server_user_id);
//        System.err.println("当前登录服务人员参与此订单竞拍次数 = " + auctionCountByServerId);
        Integer result;
        if(auctionCountByServerId > 0){
            //执行更新竞拍金额的操作
            PageData update = new PageData();
            update.put("order_id",order_id);
            update.put("auction_amount",pd.get("auction_amount"));
            update.put("auction_update_time",new Date());
            result = (int) daoSupport.update(mapper+"edit", update);
        }else{
            //查询该订单下参与的竞拍人数是否大于最大参数人数
            Integer auctionCount = (int)daoSupport.findForObject(mapper+"auctionCount", pd.get("order_id"));
//            System.err.println("auctionCount = " + auctionCount);
            if (auctionCount >= maxAuctionCount) {
                throw new ServiceException("竞拍失败:此订单已经有"+auctionCount+"人参与竞价!最大竞拍人数为:"+maxAuctionCount);
            }
            //填入默认值
            pd = addDefaultValue(pd);
            result = (int) daoSupport.save(mapper+"save", pd);
        }

        return result;
    }


    @Override
    public int edit(PageData pd) throws Exception {

        return (int) daoSupport.update(mapper+"edit", pd);
    }


    @Override
    public int delete(Integer order_id) throws Exception {

        PageData pd = new PageData();
        pd.put("order_id",order_id);

        return (int) daoSupport.delete(mapper+"deleteById", pd);
    }

    @Override
    public int deleteAll(String[] DATA_IDS) throws Exception {
        return (int)daoSupport.batchDelete(mapper+"deleteAll", DATA_IDS);
    }



    @Override
    public List<PageData> list(PageData pd) throws Exception {
        return (List<PageData>) daoSupport.findForList(mapper+"list",pd);
    }

    @Override
    public PageData findById(String order_id) throws Exception {
        PageData pd = new PageData();
        pd.put("order_id",order_id);
        return (PageData) daoSupport.findForObject(mapper+"list", pd);
    }

    @Override
    public List<PageData> findByOrderId(Integer order_id) throws Exception {
        PageData pd = new PageData();
        pd.put("order_id",order_id);
        return (List<PageData>) daoSupport.findForList(mapper+"list",pd);
    }

    @Override
    public Integer findByOrderIDAndServerID(Integer order_id, String server_user_id) throws Exception {
        return findByOrderIdAndServerId(order_id,server_user_id);
    }

    @Override
    public void clearAuctionSuccess(Integer order_id) throws Exception {
        clearAuctionSuccessToZero(order_id);
    }
    /**
     * 将订单ID下的所有竞拍数据的has_success改为0
     * @param order_id
     * @throws Exception
     */
    private void clearAuctionSuccessToZero(Integer order_id) throws Exception {
        PageData pd = new PageData();
        pd.put("order_id",order_id);
        pd.put("has_success",0);
        daoSupport.save(mapper+"editByOrderId", pd);
    }


    /**
     * 通过订单id与参与竞拍的司机或承运商的id查询服务人员参与此订单竞拍的次数
     * 默认最大数为0
     * 如果为1，则不进行新增操作 执行更新竞拍金额操作
     * @param order_id
     * @param server_user_id
     * @return
     * @throws Exception
     */
    private Integer findByOrderIdAndServerId(Integer order_id, String server_user_id) throws Exception {
        PageData pageData = new PageData();
        pageData.put("order_id",order_id);
        pageData.put("server_user_id",server_user_id);
        return (int)daoSupport.findForObject(mapper+"auctionCountByServerUserID", pageData);
    }

    /**
     * 检测必填项数据
     * @param pd
     */
    private void checkNonEmptyData(PageData pd){
        if( pd.get("order_id") ==null ||"".equals(pd.get("order_id").toString())){
            throw new ServiceException("竞拍失败:订单ID(order_id)不能空");
        }
        if( pd.get("auction_amount") ==null ||"".equals(pd.get("auction_amount").toString())){
            throw new ServiceException("竞拍失败:竞拍金额(auction_amount)不能空");
        }
        if( Double.parseDouble(pd.get("auction_amount").toString()) < minAuctionAmount){
            throw new ServiceException("竞拍失败:竞拍金额(auction_amount)不得低于"+minAuctionAmount);
        }

    }



    /**
     * 新增填入默认值
     * @param pd
     * @return
     */
    private PageData addDefaultValue(PageData pd) {
        //获取当前登录用户数据
        PageData currentUser = getCurrentUser();

        pd.put("auction_id", UuidUtil.get32UUID());
        pd.put("server_user_id",getCurrentUserID());//竞拍人ID  司机/承运商的user_id
        pd.put("server_user_name",currentUser.get("avatar"));//竞拍人的avatar  对应司机/承运商姓名
        pd.put("server_driver_phone",currentUser.get("phone"));//司机联系电话
        pd.put("auction_add_time",new Date());//第一次竞拍时间
        pd.put("has_success",0);//竞拍是否成功 0-不成功 1成功

        return pd;
    }

    /**
     * 获取当前登录用户数据
     * @return
     */
    private PageData getCurrentUser() {
        return (PageData) SecurityUtils.getSubject().getSession().getAttribute("currentUser");
    }
    private String getCurrentUserID(){
        PageData pd = (PageData) SecurityUtils.getSubject().getSession().getAttribute("currentUser");
        String user_id = pd.get("user_id").toString();
        return user_id;

    }

}
